package com.htdata.iiot.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RandomDate {
    private static Logger logger = LogManager.getLogger(RandomDate.class);
    /**
     * 获取随机日期
     * @param startDate 起始日期，格式为：yyyy-MM-dd
     * @param endDate 结束日期，格式为：yyyy-MM-dd
     * @return
     */
    public static long randomDate(String startDate, String endDate){
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = format.parse(startDate);
            Date end = format.parse(endDate);

            if(start.getTime() >= end.getTime()){
                logger.error("开始时间大于等于结束时间,返回当时服务器时间戳！！！");
                return System.currentTimeMillis();
            }

            long date = random(start.getTime(),end.getTime());

            return date;
        } catch (Exception e) {
            logger.error("输入的时间格式为 -> yyyy-MM-dd");
            e.printStackTrace();
        }
        return System.currentTimeMillis();
    }

    private static long random(long begin,long end){
        long rtn = begin + (long)(Math.random() * (end - begin));
        if(rtn == begin || rtn == end){
            return random(begin,end);
        }
        return rtn;
    }
}
